import { getAllCategory } from '@/api/category'
import { topCategory } from '@/api/constants'
// console.log(topCategory)
// 分类模块
const state = {
  // 分类信息集合
  list: topCategory.map(item => {
    return { name: item }
  })
}

const mutations = {
  setList (state, payload) {
    state.list = payload
  },
  show (state, item) {
    // 找到目标对象
    const current = state.list.find(v => v.id === item.id)
    // 修改目标对象状态，显示
    // console.log(current)
    current.open = true
  },
  hide (state, item) {
    // 找到目标对象
    const current = state.list.find(v => v.id === item.id)
    // 修改目标对象状态，隐藏
    current.open = false
  }
}

const actions = {
  async getList ({ commit }) {
    const { result } = await getAllCategory()
    // 为每个一级分类添加一个 open 字段用于控制二级分类开启或者关闭
    result.forEach(item => {
      item.open = false
    })
    // commit 修改数据
    // console.log(result)
    commit('setList', result)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
